package com.eascs.archive.controller.v1;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.vo.LoanApplyEntity;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.detail.service.LoanDetailService;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.app.runtime.RuntimeSetting;
import com.eascs.archive.controller.credit.ArchiveQueryController;
import com.eascs.archive.dao.ArchiveRecordDao;
import com.eascs.archive.dubbo.ArchiveTask;
import com.eascs.archive.entity.*;
import com.eascs.archive.service.ArchiveAdminService;
import com.eascs.archive.service.ArchiveBorrowService;
import com.eascs.archive.service.ArchiveService;
import com.eascs.archive.untils.ArchiveConstants;
import com.eascs.dubbo.loan.service.LoanInfoServiceImpl;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.dictionary.DicDataService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@RequestMapping("/archive/v1")
@Controller(value = "archiveControllerV1")
public class ArchiveController extends BaseMasterViewController {
	final static int PAGE_SIZE = 15;

	private final Logger logger = LoggerFactory.getLogger(ArchiveQueryController.class);
	
	@Autowired
	private ArchiveTask           archiveTask;
	@Autowired
	private ArchiveAdminService   archiveAdminService;
	@Reference
	private WorkFlowService       workFlowService;
	@Reference
	private DicDataService        dicDataService;
	@Autowired
	private ArchiveRestController ctr;
	@Autowired
	private ArchiveBorrowService  archiveBorrowService;
	@Autowired
	private O2oLoanapplyService   o2oLoanapplyService;
	@Autowired
	private LoanDetailService     loanDetailService;
	@Autowired
	private O2oLoanUserService    o2oLoanUserService;
	@Autowired
	private ArchiveService        archiveService;
	@Autowired
	private LoanInfoServiceImpl   loanInfoService;
	@Autowired
	private ArchiveRecordDao      archiveRecordDao;

	@Value("${o2o.admin.iframe.domain}")
	private String domain;

	@Value("${o2o.admin.agreeInfo}")
	private String agreeInfoUrl;
	
	@Reference
	SysOrgService sysOrgService;

	@RequestMapping("/queryList")
	public String queryArchiveList(ArchiveLoanEntity param) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "archiveMananger");
		if (param.getPageSize() == null || param.getPageSize() == 0) {
			param.setPageSize(PAGE_SIZE);
		}
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		param.setXdjlNo(no);
		
		ModelResult<PageResult<Object[]>> modelResult = archiveAdminService.queryListPage(param, param.getPageSize(),
				param.getPageIndex());
		if (modelResult.isSuccess()) {
			PageResult<Object[]> pageResult = modelResult.getModel();
			String[] titles = { "贷款单号", "平台", "信贷经理", "借款人姓名", "放款银行", "放款日期	", "归档完成时间", "存柜档案编号", "归档状态" };
			SelectDataOption[] selectDataOptions = { null, null, null, null, new SelectDataOption("BANKTYPEO2O"), null,
					null, null, new SelectDataOption("PLACEONFILE") };
			PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, "/archive/v1/queryList?pageIndex=");

			Button tBtn =  ButtonHelper.createOpenButton(null, "/archive/v1/borrow?referId=") ;
			tBtn.setPermissionCode("gdglCheckButton");
			tBtn.setShowButtonFilter(new ShowButtonFilter() {
				@Override
				public boolean filter(Object param) {
					Object[] params = (Object[]) param;
					String bankName = params[5].toString();
					String state = params[9].toString();

					if (StringUtils.isBlank(state) || StringUtils.isBlank(bankName))
						return false;
					tBtn.setUrl("/archive/v1/borrow?billCode=" + params[1] + "&state=" + state + "&referId=");

					if ((state.equals("CLO") || state.equals("RUN") || state.equals("NEW"))
							&& (!StringUtils.equals(bankName, "CCB") || !StringUtils.equals(bankName, "HXBC")))
						return true;
					return false;
				}
			});
			Button[] titleButtons = new Button[] { tBtn };
			paginationInfo.setTitleButtons(titleButtons);
			paginationInfo.setBuildPagingNavigation(true);
			paginationInfo.setFirstRenderColumnIndex(1);
			paginationInfo.setSelectDataOptions(selectDataOptions);
			ViewContext.put("paginationInfo", paginationInfo);
			ViewContext.put("archiveLoan", param);
		}
		return "/archive/v1/archiveAdminList";
	}

	@RequestMapping("/repeatGdList")
	public String repeatGdList(ArchiveLoanEntity param) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "DH_BCGD");
		if (param.getPageSize() == null || param.getPageSize() == 0) {
			param.setPageSize(PAGE_SIZE);
		}
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		param.setXdjlNo(no);
		
		ModelResult<PageResult<Object[]>> modelResult = archiveAdminService.repeatGdList(param, param.getPageSize(),
				param.getPageIndex());
		if (modelResult.isSuccess()) {
			PageResult<Object[]> pageResult = modelResult.getModel();
			String[] titles = { "单据号", "贷款单号", "借款人", "经办平台", "信贷经理", "放款银行", "放款日期", "存柜档案编号", "归档类型", "流程状态",
					"创建时间" };
			SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("BANKTYPEO2O"),
					null, null, new SelectDataOption("OTO_LOAN_TYPE"), new SelectDataOption("parWFStutus"), null };
			PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles,
					"/archive/v1/repeatGdList?pageIndex=");
//			Button delete = ButtonHelper.createAjaxConfirmButton("删除", "");
//			delete.setShowButtonFilter(new ShowButtonFilter() {
//				@Override
//				public boolean filter(Object param) {
//					Object[] params = (Object[]) param;
//					int stat = Integer.parseInt(params[11] + "");
//					delete.setUrl("/archive/rest/v1/deleteRepeatArchiveRecord?gdId=" + params[1] + "&v=");
//					if (stat == -1 || stat == 3)
//						return true;
//					return false;
//				}
//			});
//			Button update = ButtonHelper.createOpenButton("修改", "");
//			update.setShowButtonFilter(new ShowButtonFilter() {
//				@Override
//				public boolean filter(Object param) {
//					Object[] params = (Object[]) param;
//					int stat = Integer.parseInt(params[11] + "");
//					update.setUrl("/archive/v1/repeatGdNewDes?gdId=" + params[1] + "&billCode=" + params[3] + "&v=");
//					if (stat == -1 || stat == 3)
//						return true;
//					return false;
//				}
//			});
//			Button start = ButtonHelper.createAjaxButton("启动流程", "");
//			start.setShowButtonFilter(new ShowButtonFilter() {
//				@Override
//				public boolean filter(Object param) {
//					Object[] params = (Object[]) param;
//					int stat = Integer.parseInt(params[11] + "");
//					start.setUrl("/archive/rest/v1/gdRepeatStart?gdId=" + params[1] + "&v=");
//					if (stat == -1 || stat == 3)
//						return true;
//					return false;
//				}
//			});
//			Button[] titleButton = new Button[] { update, delete, start };
			Button tBtn = ButtonHelper.createOpenButton(null, "");
			tBtn.setShowButtonFilter(new ShowButtonFilter() {
				@Override
				public boolean filter(Object param) {
					Object[] params = (Object[]) param;
					tBtn.setUrl("/archive/v1/repeatGdNewDes?gdId=" + params[1] + "&billCode=" + params[3] + "&v=");
					return true;
				}
			});
			Button[] titleButtons = new Button[] { tBtn };
			paginationInfo.setTitleButtons(titleButtons);
			paginationInfo.setBuildPagingNavigation(true);
			paginationInfo.setFirstRenderColumnIndex(2);
			//paginationInfo.setMoreButtons(titleButton);
			paginationInfo.setSelectDataOptions(selectDataOptions);
			ViewContext.put("paginationInfo", paginationInfo);
			ViewContext.put("archiveLoan", param);
		}
		return "/archive/v1/repeatGd/repeatGdList";
	}

	@RequestMapping("/repeatGdNewDes")
	public String repeatGdNewDes(String billCode, String gdId,@RequestParam(required=false)String formTypeId) {
		String url = "/archive/v1/repeatGd/repeatGdNewDes";
		if (StringUtils.isNotBlank(billCode)) {
			int isHideBtn = 1;// 1显示、2隐藏
			ModelResult<LoanApplyEntity> modelResult = loanInfoService.getLoanapplyInfo(null, billCode);
			LoanApplyEntity loanInfo = modelResult.getModel();
			if (loanInfo == null) {
				ViewContext.put("errorMsg", "数据异常，贷款单不存在");
				return url;
			}
			if (StringUtils.isBlank(loanInfo.getBankLoanName())) {
				ViewContext.put("errorMsg", "数据异常，放款银行为空");
				return url;
			}
			List<FieldEntity> fields = archiveService.getFieldListAll();
			List<FieldEntity> cwFields = archiveService.getFieldListAll();
			String bankTypeId = ArchiveConstants.getBankTypeId(loanInfo.getBankLoanName());
			if (StringUtils.isNotBlank(gdId)) {
				ArchiveRecordRepeatEntity gdRepeatEntity = archiveRecordDao.queryArchiveRepeatRecordById(gdId);
				ViewContext.put("gdRepeatEntity", gdRepeatEntity);
				convertJson(gdRepeatEntity.getContentJson(), fields);
				convertJson(gdRepeatEntity.getCwContentJson(), cwFields);
				if (gdRepeatEntity.getWfState() != -1 && gdRepeatEntity.getWfState() != 3) {
					isHideBtn = 2;
				}
			}
			if(StringUtils.isBlank(formTypeId))
				formTypeId=ArchiveConstants.FORMTYPE_ARCHIVE_INFO;
			ViewContext.put("formTypeId", formTypeId);
			ViewContext.put("gdId", gdId);
			ViewContext.put("fields", fields);
			ViewContext.put("cwFields", cwFields);
			ViewContext.put("loanInfo", loanInfo);
			ViewContext.put("bankTypeId", bankTypeId);
			ViewContext.put("isHideBtn", isHideBtn);
		}
		return url;
	}

	private void convertJson(String json, List<FieldEntity> fields) {
		if(StringUtils.isNotBlank(json)){
			JSONObject obj = JSONObject.parseObject(json);
			for (FieldEntity f : fields) {
				String fieldValue = obj.getString(f.getFieldName());
				if (StringUtils.isNotBlank(fieldValue))
					f.setFieldValue(fieldValue);
			}
		}
	}

	@RequestMapping(value = "/borrow", method = RequestMethod.GET)
	public String borrow(String referId, String state, String billCode) {
		ctr.buildData(referId, null);
		ArchiveRecordEntity record = archiveBorrowService.queryArchiveExist(referId);
		ViewContext.put("state", state);
		ViewContext.put("record", record);

		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCodeDetail(billCode);
		String place = loanapply.getIsPlaceOnFile();
		boolean afterLoanArchive = StringUtils.isNotBlank(place) && !"NEW".equals(place);
		boolean archiveRepeat = archiveRecordDao.hasArchiveRepeatRecordByLoanApplyNo(loanapply.getLoanapplyNo());

		if (state.equals("CLO") || state.equals("RUN") ){
			ViewContext.put("isNotArchive", false);
		} else{
			ViewContext.put("isNotArchive", true);
		}
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("agreeInfoUrl", agreeInfoUrl);
		ViewContext.put("afterLoanArchive", afterLoanArchive);
		ViewContext.put("archiveRepeat", archiveRepeat);

		return "archive/v1/borrowDes";
	}

	@RequestMapping(value = "/borrowApprovalDes", method = RequestMethod.GET)
	public String borrowApproval(String bid) {
		ArchiveBorrowEntity entity = archiveBorrowService.queryArchiveBorrowById(bid);
		String loanapplyNo = entity.getLoanapply_no();
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findContinueById(loanapplyNo);
		String isNotContinue = null;
		O2oLoanapplyEntity loanapplyEntity = loanDetailService.queryLoanapplyBillCode(loanapply.getLoanapplyNo(),
				loanapply.getLoanId(), loanapply.getBillCode(), loanapply.getCreateDate());
		if (loanapplyEntity != null) {
			loanapply.setContinueLoanParenNo(loanapplyEntity.getBillCode());
			isNotContinue = "Y";
		}
		ctr.buildData(loanapplyNo, bid);
		ViewContext.put("isNotContinue", isNotContinue);
		ViewContext.put("loanapply", loanapply);
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("domain", domain);
		if (StringUtils.isNotBlank(entity.getSend_no())) {
			ViewContext.put("showSendInfo", "true");
			ViewContext.put("hidenBtn", "true");
		}
		ViewContext.put("referId", bid);
		// ViewContext.put("archiveBorrow", entity);
		return "/archive/v1/borrowApprovalDes";
	}

	/** 开发环境，模拟定时调用 */
	@RequestMapping(value = "/test/schedular", method = RequestMethod.GET)
	public void archiveHQ() {
		RuntimeSetting runtimeSetting = RuntimeSetting.get();
		if (!runtimeSetting.getEnv().equals("prod")) { // 非生产环境
			archiveTask.startUpPlaceOnFile();
		}
	}

	@RequestMapping(value = "/importApproval", method = RequestMethod.GET)
	public String importApproval() {
		return "/archive/v1/import/loanDataImport";
	}
}

